package com.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//post方式乱码过滤器
public class CharacterSetFilter implements Filter {
	private String encoding = "" ;

	public void init(FilterConfig filterConfig) throws ServletException {
		encoding = filterConfig.getInitParameter("encoding") ;
	}
	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		// 将请求和响应转换为与协议相关的请求和响应
		HttpServletRequest request;
		HttpServletResponse response;
		System.out.println("aaaaaaaaaa");
		try {
			request = (HttpServletRequest) req;
			response = (HttpServletResponse) res;
		} catch (ClassCastException e) {
			throw new ServletException("non-HTTP request or response");
		}
		request.setCharacterEncoding(encoding) ;
		response.setContentType("text/html;charset=" + encoding) ;
		//放行
		chain.doFilter(request, response) ;
	}
}
